package com.pvdnc.xdynamic.loader.module;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.pm.ApplicationInfo;
import android.content.res.Resources;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;

import com.pvdnc.xdynamic.loader.mirror.android.app.ActivityThread;
import com.pvdnc.xdynamic.loader.mirror.android.app.ContextImpl;
import com.pvdnc.xdynamic.loader.mirror.android.app.LoadedApk;
import com.pvdnc.xdynamic.loader.mirror.android.content.res.CompatibilityInfo;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

public class ModuleContext {
    private static final String TAG=ModuleContext.class.getSimpleName();

    private Context mHostContext;
    public ModuleContext(Context hostContext){
        mHostContext=hostContext.getApplicationContext();//防止传入Activity导致包名为null
    }

    private Context mModuleContext;

    public void attach(ApplicationInfo ai,ModuleDir dir,ClassLoader cl,Resources res) throws IOException {
        Object at=ActivityThread.sCurrentActivityThread.get();
        Object compatInfo= CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO.get();
        Object loadedApk= ActivityThread.getPackageInfoNoCheck.call(at,
                ai,compatInfo);
        //LoadedApk里设置了各个目录
        LoadedApk.mAppDir.set(loadedApk,dir.getModuleApkFile().getAbsolutePath());
        LoadedApk.mDataDir.set(loadedApk,dir.getModuleDataDir());
        LoadedApk.mLibDir.set(loadedApk,dir.getLibDir().getAbsolutePath());
        LoadedApk.mResDir.set(loadedApk,dir.getModuleDir().getAbsolutePath());
        //数据库目录
        LoadedApk.mDataDirFile.set(loadedApk,new File(dir.getModuleDataDir()));
        //使用自定义类加载器
        LoadedApk.mClassLoader.set(loadedApk,cl);

        Context context= ContextImpl.createAppContext.call(at,loadedApk);
        //module资源
        ContextImpl.mResources.set(context,res);
        //Appops包名（bypass InputMethodManagerService对EditorInfo的检查）
        handlePkgName(context);
        //包装
        mModuleContext=new Wrapper(context,ai.theme);
    }

    private void handlePkgName(Context context){
        String opPackageName=ContextImpl.mOpPackageName.get(mHostContext);
        if(opPackageName==null)
            opPackageName=mHostContext.getPackageName();
        ContextImpl.mOpPackageName.set(context,opPackageName);
        //mBasePackageName
        String basePackageName=ContextImpl.mBasePackageName.get(mHostContext);
        if(basePackageName==null)
            basePackageName=mHostContext.getPackageName();
        ContextImpl.mBasePackageName.set(context,basePackageName);
    }

    public Context get(){
        return mModuleContext;
    }

    private class Wrapper extends ContextThemeWrapper {

        public Wrapper(Context base,int themeId) {
            super(base,themeId);
            setTheme(themeId);//应用主题
        }

        private LayoutInflater mInflater;

        private LayoutInflater getInflater(){
            if(mInflater==null) {
                LayoutInflater inflater= (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
                Objects.requireNonNull(inflater);
                mInflater= inflater.cloneInContext(this);
            }
            return mInflater;
        }

        @Override
        public Context getApplicationContext() {
            Log.d(TAG,"redirect app context to base context");
            return this;//防止多次调用getApplicationContext
        }

        @Override
        public Object getSystemService(String name) {
            if(LAYOUT_INFLATER_SERVICE.equals(name)){//资源相关服务，走原始流程
                return getInflater();
            }
            Log.d(TAG,"redirect getSystemService:"+name+" to host context:"+mHostContext);
            return mHostContext.getSystemService(name);
        }
    }
}
